import storageService from '@/service/storageService';
import userService from '@/service/userService';

const userModule = {
  namespaced: true,
  state: {
    token: storageService.get(storageService.USER_TOKEN),
    userinfo: JSON.parse(storageService.get(storageService.USER_INFO)),
  },
  mutations: {
    SET_TOKEN(state, token) {
      storageService.set(storageService.USER_TOKEN, token);
      state.token = token;
    },
    SET_USERINFO(state, userinfo) {
      storageService.set(storageService.USER_INFO, JSON.stringify(userinfo));
      state.userinfo = userinfo;
    },
  },
  actions: {
    register(commit, { name, telephone, password }) {
      return new Promise((resolve, reject) => {
        userService.register(this.user).then((res) => {
          // 保存token
          // console.log(res.data.data.token);
          // console.log(storageService.USER_TOKEN);

          // storageService.set(storageService.USER_TOKEN, res.data.data.token);// 第一种
          // this.$store.commit('userModule/SET_TOKEN', res.data.data.token);// 第2种
          this.SET_TOKEN(res.data.data.token);// 第3种

          return userService.info();
        }).then((responce) => {
          // 第一种
          // storageService.set(storageService.USER_INFO, JSON.stringify(responce.data.data.user));
          // this.$store.commit('userModule/SET_USERINFO', responce.data.data.user);//第2种
          this.SET_USERINFO(responce.data.data.user);// 第3种
          // 跳转主页
          this.$router.replace({ name: 'Home' });
        }).catch(err) => {
          reject(err);
        };
      });
    },
  },
};

export default userModule;
